import { ref,nextTick, computed } from "vue";
import {
  createGoodsSkusCard,
  updateGoodsSkusCard,
  deleteGoodsSkusCard,
  sortGoodsSkusCard,
  createGoodsSkusCardValue,
  updateGoodsSkusCardValue,
  deleteGoodsSkusCardValue,
  chooseAndSetGoodsSkusCard
} from "@/api/goods";

import { 
   useArrayMoveUp,
   useArrayMoveDown,
  cartesianProductOf} from "@/composables/util";
//当前商品ID
export const goodsId = ref(0);

//规格选项列表
export const sku_card_list = ref([])

//对应规格选项的表格数据
export const sku_list = ref([])

//初始化规格选项列表
export function initSkuCardList(d) {
  sku_card_list.value = d.goodsSkusCard.map((item) => {
    item.text = item.name
    item.loading = false
    item.goodsSkusCardValue.map((v) => {
      v.text = v.value || "属性值"
      return v
    })
    return item
  })

  console.log(d)
  sku_list.value = d.goodsSkus
  
}

//添加规格选项
export const btnloading = ref(false);
export function addSkuCardEvent() {
  btnloading.value = true;
  createGoodsSkusCard({
    goods_id: goodsId.value,
    name: "规格选项",
    order: 50,
    type: 0,
  })
    .then((res) => {
      sku_card_list.value.push({
        ...res,
        text: res.name,
        loading: false,
        goodsSkusCardValue: [],
      });
    })
    .finally(() => {
      btnloading.value = false;
    });
}

//修改规格选项
export function handleUpdate(item) {
  item.loading = true;
  updateGoodsSkusCard(item.id, {
    goods_id: item.goods_id,
    name: item.text,
    order: item.order,
    type: 0,
  })
    .then((res) => {
      item.name = item.text;
    })
    .catch((err) => {
      item.text = item.name;
    })
    .finally(() => {
      item.loading = false;
    });
}

//删除规格选项
export function handleDelete(item) {
  item.loading = true;
  deleteGoodsSkusCard(item.id).then((res) => {
    const i = sku_card_list.value.findIndex((o) => o.id == item.id);
    if (i != -1) {
      sku_card_list.value.splice(i, 1);
    }
    getTableData()
  })
}

//排序规格选项
export const bodyloading = ref(false);
export function sotCard(action, index) {
  //深拷贝生成一个完全独立的新对象oList,类似于备份，互不影响
  let oList = JSON.parse(JSON.stringify(sku_card_list.value));
  //调整元素位置
  let func = action == "up" ? useArrayMoveUp : useArrayMoveDown;
  func(oList, index);

  //为排序后的每个元素创建新数组，包含两个属性
  let sortData = oList.map((o, i) => {
    return {
      id: o.id,
      order: i + 1, //新的排序号
    };
  });
  bodyloading.value = true;
  sortGoodsSkusCard({
    sortdata: sortData,
  })
    .then((res) => {
      func(sku_card_list.value, index)
      getTableData()
    })
    .finally(() => {
      bodyloading.value = false;
    });
}

//选择设置规格
export function handleChooseSetGoodsSkusCard(id,data){
  let item = sku_card_list.value.find(o=>o.id == id)
  item.loading = true
    chooseAndSetGoodsSkusCard(id,data).then(res=>{
        console.log(res)
        item.name = item.text = res.goods_skus_card.name
        item.goodsSkusCardValue = res.goods_skus_card_value.map(o=>{
          o.text = o.value || "属性值"
          return o
        })
      getTableData()
    }).finally(()=>{
      item.loading = false
    })
}

//初始化规格值
export function initSkuCardItem(id) {
  const item = sku_card_list.value.find((o) => o.id == id);
  const loading = ref(false)
  const inputValue = ref("");
  const inputVisible = ref(false);
  const InputRef = ref();
  const handleClose = (tag) => {
    loading.value = true
    deleteGoodsSkusCardValue(tag.id).then(res=>{
      let i =  item.goodsSkusCardValue.findIndex(o=>o.id === tag.id)
      if(i != -1){
        item.goodsSkusCardValue.splice(i,1)
      }
      getTableData()
    }).finally(()=>{
      loading.value = false
    })
  };
  const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
      InputRef.value.input.focus();
    });
  };
  
  const handleInputConfirm = () => {
    if(!inputValue.value){
    inputVisible.value = false
      return 
    }
    loading.value = true
    createGoodsSkusCardValue({
      goods_skus_card_id:id,
      name:item.name,
      order:50,
      value:inputVisible.value
    }).then(res=>{
      item.goodsSkusCardValue.push({
        ...res,
        text:res.value
      })
      getTableData()
    }).finally(()=>{
      inputVisible.value = false
      inputValue.value = ""
      loading.value = false
    })
    
  };

  const handleChange = (value,tag)=>{
    // console.log(value); --修改之后的值
    loading.value = true
    updateGoodsSkusCardValue(tag.id,{
        "goods_skus_card_id": id,
        "name": item.name, //规格选项名称
        "order": tag.order,
        "value": value
    }).then(res=>{
      tag.value = value
      getTableData()
    }).catch(err=>{
      tag.text = tag.value
    }).finally(()=>{
      loading.value = false
    })
  }

  return {
    item,
    inputValue,
    inputVisible,
    InputRef,
    handleClose,
    showInput,
    handleInputConfirm,
    loading,
    handleChange
  }
}

//初始化表格
export function initSkuTable(){
    //对规格选项名称的数组进行过滤，将具有规格值内容的规格选项数组过滤出来,并赋值给skuLabels
    const skuLabels = computed(()=>sku_card_list.value.filter(v=>v.goodsSkusCardValue.length > 0))

    //获取表头--使用computed是因为可以让数据变成响应式
    const tableThs = computed(()=>{
      let length = skuLabels.value.length //规格选项的长度--合并多少列
      return [{
        name:"商品规格",
        colspan:length,
        width:"",
        rowspan:length > 0 ? 1 : 2
      },{
        name:"销售价",
        width:"100",
        rowspan:2
      },{
        name:"市场价",
        width:"100",
        rowspan:2
      },{
        name:"成本价",
        width:"100",
        rowspan:2
      },{
        name:"库存",
        width:"100",
        rowspan:2
      },{
        name:"体积",
        width:"100",
        rowspan:2
      },{
        name:"重量",
        width:"100",
        rowspan:2
      },{
        name:"编码",
        width:"100",
        rowspan:2
      }]
    })
    return {
      skuLabels,
      tableThs,
      sku_list
    }
}

//获取规格表格数据--数据联动
function getTableData(){
  setTimeout(()=>{//sku_card_list--规格选项
  if(sku_card_list.value.length === 0) return[]

  let list = [] // 用来存放所有的规格选项值
  sku_card_list.value.forEach(o=>{
    if(o.goodsSkusCardValue && o.goodsSkusCardValue.length > 0){
      list.push(o.goodsSkusCardValue)
    }
  })

  if(list.length == 0){ //二次检查
    return []
  }
  //排列组合后的数据
  let array = cartesianProductOf(...list)

  //先获取之前的规格列表，将规格Id排序之后转化成字符串
  let beforeSkuList = JSON.parse(JSON.stringify(sku_list.value)).map(o=>{
    if(!Array.isArray(o.skus)){
      o.skus = Object.keys(o.skus).map(k=>o.skus[k])
    }
      o.skusId = o.skus.sort((a,b)=>a.id-b.id).map(s=>s.id).join(",")
      return o
  })

   sku_list.value = []
   sku_list.value = array.map(skus=>{

    let oo =  getBeforeSkuItem(JSON.parse(JSON.stringify(skus)),beforeSkuList)

    return {
      code:oo?.code || "",
      cprice:oo?.cprice || "",
      goods_id:goodsId.value,
      image:oo?.image ||"",
      oprice:oo?.oprice ||"0.00",
      pprice:oo?.pprice ||"0.00",
      skus,
      stock:oo?.stock ||0,
      volumn:oo?.volumn ||0,
      weight:oo?.weight ||0
    }
  })},200)
}

//在规格变更的情况下，通过ID字符串的子串匹配，关联旧规格组合，保留原有业务，避免规格调整导致业务丢失
function getBeforeSkuItem(skus,beforeSkuList){
  let skusId =  skus.sort((a,b)=>a.id-b.id).map(s=>s.id).join(",")
   return  beforeSkuList.find(o=>{
    if(skus.length > o.skus.length){ //新增
        skusId.indexOf(o.skusId) != -1
    }
    return o.skusId.indexOf(skusId) != -1 //删除
  })
}